import {
  getAllDates,
  getUserConfig,
  getUserDates,
  dataKey,
  configKey
} from './dates.js';
import {
  getVersion,
  isDebugMode,
  formatDate,
  setStorage,
  generateId
} from './common.js';

main();

/**
 * @description 主函数入口
 * @author start2004
 * @since 2025-08-13
 *
 * @return {void}
 */
export async function main() {
  /**
   * @since 2025-08-12 渲染日期事件列表
   */
  await renderDates();
  // return;

  /**
   * @since 2025-08-13 监听事件，等渲染结束，await
   */
  addListener();

  /**
   * @since 2025-08-26 图标到插件商店
   */
  let version = await getVersion();
  $("#version").html(version);
  $("#version").on("click", function (){
    let language = chrome.i18n.getMessage("language");
    let url = "https://chromewebstore.google.com/detail/date-countdown/igmadampembmekbmndlidhkfblpjniac?hl="+ language;
    if(GetBrowserType() === "edge") url = "https://microsoftedge.microsoft.com/addons/detail/date-countdown/geadbdhohhgldpadppajioeaepmkjknp?hl="+ language.replace("_", "-");
    window.open(url);
  });

  /**
   * @since 2025-08-20 测试按钮，新开popup页面
   */
  let debug = await isDebugMode();
  if(debug){
    $("#debug-btn").show();
    $("#debug-btn").on('click', function(e) {
      open("popup.html");
    });
  } else {}

  /**
   * @since 2025-09-25 通知background，检查是否有任务到期
   */
  chrome.runtime.sendMessage({action: "check-due-tasks"});
}

/**
 * @description 渲染日期列表
 * @author start2004
 * @since 2025-08-11
 *
 * @return {void}
 */
async function renderDates() {
  /**
   * @since 2025-08-12 渲染骨架屏
   */
  renderSkeleton();

  /**
   * @since 2025-08-12 获取数据
   */
  let dates = await getAllDates();

  /**
   * @since 2025-08-11 按级别图标，过滤数据
   */
  let currentFilter = $(`.filter-icon.active`).data("level");
  if (currentFilter !== undefined) {
    dates = dates.filter(item => item.level === currentFilter);
  } else {}

  /**
   * @since 2025-08-11 按日期排序，从小到大
   */
  dates.sort((a, b) => new Date(a.date) - new Date(b.date));

  /**
   * @since 2025-08-12 拼接html
   */
  let htmlArray = [];
  dates.forEach(item => {
    htmlArray.push(getDateItemHtml(item));
  });
  $("#date-container").html(htmlArray.join(''));

  /**
   * @since 2025-09-25 用户是否选中节假日
   */
  clickHolidayBtn(false);

  /**
   * @since 2025-08-13 监听，编辑和删除按钮
   * @since 2025-08-18 每次渲染要重新监听，没有放到初始化监听函数
   */
  $(".edit-btn").click(function() {
    openWindow($(this).data("id"));
  });
  $(".delete-btn").click(function() {
    deleteDateItem($(this).data("id"));
  });

  /**
   * @since 2025-08-13 定位到第一个未过期的日期
   */
  let n = $('div.date-item.past').length;
  $('#date-container').scrollTop(90*n+10);
}

/**
 * @description 增加监听事件，初始化
 * @author start2004
 * @since 2025-08-13
 *
 * @return {void}
 */
function addListener(){
  /**
   * @since 2025-08-13 文字标题
   */
  $("#form-title").text(chrome.i18n.getMessage("form_title"));
  $("#form-date").text(chrome.i18n.getMessage("form_date"));
  $("#form-submit").text(chrome.i18n.getMessage("form_submit"));

  /**
   * @since 2025-08-13 加载日历插件
   */
  let dayOfWeekStart = 0;
  let lang = "en";
  let format = "M. d, Y";
  const year = new Date().getFullYear();
  switch (chrome.i18n.getMessage("language")){
    case "zh_CN":
      dayOfWeekStart = 1;
      lang = "ch";
      format = "Y-m-d";
      break;
    case "en":

    default:
  }
  jQuery.datetimepicker.setLocale(lang);
  $("#date-input").datetimepicker({
    dayOfWeekStart: dayOfWeekStart, // 一周第一天星期几开始
    format: format, // 格式化时间
    timepicker: false,  // 时间选项开关
    todayButton: false, // 今天按钮开关
    width: "100%",
    yearStart: year-1, // 控制可选年份
    yearEnd: year+3
  });

  /**
   * @since 2025-08-14 日期事件-新增按钮
   * @since 2025-08-14 节假日数据-是否合并-按钮
   */
  $('#add-btn').on('click', function() {
    openWindow();
  });
  $("#holiday-btn").on("click", function (){
    clickHolidayBtn(true);
  });
  $("#add-btn").attr("title", chrome.i18n.getMessage("add_title"));
  $("#holiday-btn").attr("title", chrome.i18n.getMessage("holiday_title"));

  /**
   * @since 2025-08-13 监听-新窗口
   * 提交按钮，关闭按钮，其他区域关闭，日期事件级别选择
   */
  $('#date-form').on('submit', function(e) {
    e.preventDefault(); // 阻止默认提交行为
    handleFormSubmit(e);
  });
  $('#form-close').on('click', function() {
    $("#window").hide();
  });
  $('#window').on('click', function(e) {
    if (e.target === this) $("#window").hide();
  });
  $(".color-swatch").on('click', function(e) {
    const level = parseInt($(this).data("level"));
    setChecked(level);
  });

  /**
   * @since 2025-08-13 图标过滤
   */
  $(".filter-icon").on('click', function(e) {
    const level = parseInt($(this).data("level"));
    setFilter(level);
  });
}

/**
 * @description 新增日期事件的html
 * @author start2004
 * @since 2025-08-11
 *
 * @param {object} item - 日期数据
 * @return {string} 日期事件的html
 */
function getDateItemHtml(item) {
  let html = "";

  /**
   * @since 2025-08-11 检查是否过期
   */
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  const itemDate = new Date(item.date);
  itemDate.setHours(0, 0, 0, 0);
  if (itemDate < today) {
    html += `<div class="date-item past">`;
  } else {
    html += `<div class="date-item not-past">`;
  }

  /**
   * @since 2025-08-12 item.id存在，则添加编辑和删除按钮
   */
  if(item.hasOwnProperty("id")){
    let id = item.id;
    html += `<div class="date-actions"><img class="edit-btn" data-id="${id}" src="../assets/images/edit.png"><img class="delete-btn" data-id="${id}" src="../assets/images/delete.png"></div>`;
  } else {
    html += `<div class="date-actions"><img class="delete-btn" data-id="0" src="../assets/images/delete.png"></div>`;
  }

  /**
   * @since 2025-08-11 显示还有多少天，或者已过多少天
   */
  const timeDiff = itemDate - today;
  const dayDiff = Math.ceil(timeDiff / (1000 * 60 * 60 * 24));
  let countdownText;
  if (dayDiff === 0) {
    countdownText = '<span>'+ chrome.i18n.getMessage("today") +'</span>';
  } else if (dayDiff > 0) {
    switch (chrome.i18n.getMessage("language")){
      case "zh_CN":
        countdownText = `还有<span>${dayDiff}</span>天`;
        break;
      case "en":
      default:
        countdownText = `<span>+${dayDiff}</span>&nbsp;`;
        if(dayDiff == 1){
          countdownText += 'day';
        } else {
          countdownText += 'days';
        }
    }
  } else {
    switch (chrome.i18n.getMessage("language")){
      case "zh_CN":
        countdownText = `过去<span>${-dayDiff}</span>天`;
        break;
      case "en":
      default:
        countdownText = `<span>-${-dayDiff}</span>&nbsp;`;
        if(dayDiff == -1){
          countdownText += 'day';
        } else {
          countdownText += 'days';
        }
    }
    // countdownText = chrome.i18n.getMessage("days_passed").replace("#days#", `<span>${-dayDiff}</span>`);
  }

  /**
   * @since 2025-08-11 日期块的html
   */
  html += `
    <div class="content-wrapper">
      <div class="left-content">
        <h3>${item.title}</h3>
        <p><span class="icon level-${item.level}"></span>${formatDate(item.date, chrome.i18n.getMessage("language"))}</p>
      </div>
      <div class="countdown">${countdownText}</div>
    </div>
  </div>`;

  return html;
}

/**
 * @description 渲染骨架屏
 * @author start2004
 * @since 2025-08-12
 *
 * @return {void}
 */
function renderSkeleton(){
  /**
   * @since 2025-08-12 骨架屏渲染
   */
  let skeletonHtml = '<div class="skeleton-container">';
  for (let i = 0; i < 6; i++) {
    skeletonHtml += `
      <div class="skeleton-item">
        <div class="skeleton-line full"></div>
        <div class="skeleton-line middle"></div>
        <div class="skeleton-line short"></div>
      </div>
    `;
  }
  skeletonHtml += '</div>';
  $("#date-container").html(skeletonHtml);
}



// 点击响应事件
/**
 * @description 设置节假日是否勾选
 * @author start2004
 * @since 2025-08-14
 *
 * @param {boolean} checked - 勾选状态
 *
 * @returns {void}
 */
function setHolidayCheck(checked){
  /**
   * @since 2025-08-14 勾选
   */
  if(checked) {
    $("#holiday-btn").removeClass("opacity06");
    $("#holiday-btn").attr("src", "../assets/images/check.png");
  } else {
    $("#holiday-btn").addClass("opacity06");
    $("#holiday-btn").attr("src", "../assets/images/uncheck.png");
  }
}

/**
 * @description 删除日期事件
 * @author start2004
 * @since 2025-08-13
 *
 * @param {string} id - 日期事件id
 *
 * @return {void}
 */
async function deleteDateItem(id) {
  /**
   * @since 2025-08-18 取消勾选节假日
   */
  if(id == "0") return clickHolidayBtn();

  let userObject = await getUserDates();
  let item = userObject[id];
  if(item === undefined) return;

  /**
   * @since 2025-08-14 删除数据并保存
   */
  delete userObject[id];
  await setStorage(dataKey, userObject);

  /**
   * @since 2025-08-14 重新渲染日期事件列表
   */
  renderDates();
}

/**
 * @description 过滤日期列表
 * @author start2004
 * @since 2025-08-13
 *
 * @param {int} level - 过滤级别
 *
 * @return {void}
 */
function setFilter(level) {
  /**
   * @since 2025-09-16 level是否被选中
   */
  let checked = $(`.filter-icon[data-level="${level}"]`).hasClass('active');

  /**
   * @since 2025-08-13 重置所有状态
   */
   $('.filter-icon').removeClass('active');

  /**
   * @since 2025-08-13 切换不同图标列表
   */
  if (!checked) $(`.filter-icon[data-level="${level}"]`).addClass('active');

  /**
   * @since 2025-08-13 重新渲染日期列表
   */
  renderDates();
}

/**
 * @description 设置用户选中的日期事件级别
 * @author start2004
 * @since 2025-08-14
 *
 * @param {int} level - 日期事件级别
 */
function setChecked(level){
  /**
   * @since 2025-08-13 重置所有状态
   */
  $('.color-swatch').removeClass('active');

  /**
   * @since 2025-08-14 设置选中
   */
  $(`.color-swatch[data-level="${level}"]`).addClass('active');
}

/**
 * @description 节假日按钮点击事件
 * @author start2004
 * @since 2025-08-14
 */
async function clickHolidayBtn(change){
  /**
   * @since 2025-08-14 读取配置
   * @since 2025-08-14 设置状态，保存
   */
  let userConfig = await getUserConfig();
  if(change){
    userConfig.holiday = !userConfig.holiday;
    await setStorage(configKey, userConfig);

    /**
     * @since 2025-08-14 重新渲染
     */
    renderDates();
  } else {}

  /**
   * @since 2025-08-14 设置节假日图标勾选状态
   */
  setHolidayCheck(userConfig.holiday);
}


// 编辑窗口

/**
 * @description 打开编辑窗口
 * @author start2004
 * @since 2025-08-13
 *
 * @param {int|null} id - 日期事件id
 * @return {void}
 */
async function openWindow(id = null) {
  /**
   * @since 2025-08-14 有日期事件id
   */
  if(id){
    /**
     * @since 2025-08-14 获取用户日期事件数据
     */
    let userDates = await getUserDates();
    let item = userDates[id];
    if(item === undefined){
      /**
       * @since 2025-08-14 无数据，说明日期列表，加载错误，重新渲染列表
       */
      renderDates();
      return ;
    } else {
      /**
       * @since 2025-08-14 表单标题-修改
       * @since 2025-08-14 设置表单数据
       */
      $('#window-title').text(chrome.i18n.getMessage("edit_date_event"));
      $('#date-id').val(item.id);
      $('#title-input').val(item.title);
      $('#date-input').val(formatDate(item.date, chrome.i18n.getMessage("language")));
      setChecked(item.level);
    }
  } else {
    /**
     * @since 2025-08-14 表单标题-新增
     */
    $('#window-title').text(chrome.i18n.getMessage("add_date_event"));

    /**
     * @since 2025-08-14 重置表单
     */
    $('#date-form').trigger('reset');
    $('#date-id').val('');
    setChecked(0);
  }

  /**
   * @since 2025-08-14 显示窗口
   */
  $('#window').css('display', 'flex');
}

/**
 * @description 表单提交
 * @author start2004
 * @since 2025-08-13
 *
 * @return {void}
 */
async function handleFormSubmit(e) {
  e.preventDefault();

  /**
   * @since 2025-08-14 防止重复提交
   */
  $("#form-submit").prop('disabled', true);

  /**
   * @since 2025-08-14 日期事件数据
   */
  const id = $("#date-id").val() || generateId();
  let item = {
    id: id,
    title: $("#title-input").val(),
    date: formatDate($("#date-input").val(), "zh_CN"), // 格式化Y-m-d
    level: $(`.color-swatch.active`).data('level')
  }

  /**
   * @since 2025-08-14 保存数据
   */
  let userDates = await getUserDates();
  userDates[id] = item;
  await setStorage(dataKey, userDates);

  /**
   * @since 2025-08-14 关闭窗口
   */
  $("#form-submit").prop('disabled', false);
  $("#window").hide();

  /**
   * @since 2025-08-14 重新渲染日期列表
   */
  renderDates();
}